#include "graphmanager.h"
#include "graphmanager.h"
#include <limits>

namespace Graph {

GraphManager::GraphManager(QCustomPlot *plot, QListWidget *listWidget, QObject * parent)
    : QObject(parent), plot(plot), listWidget(listWidget)
{

}

GraphData * GraphManager::AddNewGraph(const QString &name, const int &coloumn)
{
    auto graph = plot->addGraph();
    auto item = new QListWidgetItem(name, listWidget);
    //item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
    listWidget->addItem(item);
    auto it = data.insert(name, new GraphData(graph, item, coloumn, &time, Layer.GetGraphSettings(name)));
    connect(listWidget, SIGNAL(itemClicked(QListWidgetItem *)), *it, SLOT(itemChanged(QListWidgetItem *)));
    return (*it);
}

QMap<QString, GraphData *>::iterator GraphManager::DeleteGraph(QMap<QString, GraphData *>::iterator deleteElement)
{
    plot->removeGraph((*deleteElement)->GetGraph());
    delete *deleteElement;
    return data.erase(deleteElement);
}

void GraphManager::PushTimeGraph(const double &value)
{
    time.push_back(value);
}

void GraphManager::ClearData()
{
    time.clear();
    for (auto i : data)
    {
        i->ClearAll();
    }
}

QMap<QString, GraphData *> &GraphManager::GetData()
{
    return data;
}

const QCPRange &GraphManager::GetTimeRange()
{
    return TimeRange;
}

const QCPRange &GraphManager::GetValueRange()
{
    return ValueRange;
}

void GraphManager::RefreshData()
{
    TimeRange.lower = time[0];
    TimeRange.upper = time[time.size() - 1];

    ValueRange.upper = -std::numeric_limits<double>::max();
    ValueRange.lower = std::numeric_limits<double>::max();
    for (auto i : data)
    {
        if (i->IsVisible() == true)
        {
            if (i->getMax() > ValueRange.upper) ValueRange.upper = i->getMax();
            if (i->getMin() < ValueRange.lower) ValueRange.lower = i->getMin();
        }
    }
    plot->xAxis->setRange(GetTimeRange());
    plot->yAxis->setRange(GetValueRange());
    plot->replot();
}

}
